package com.aaa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: aaa-his-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-12-07 11:23
 **/
public class JwtUtils {

    //生成jwt令牌
    public static String create(String username) {
        Map<String, Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,30);
        Date expiresDate = nowTime.getTime();
        String token = JWT.create()
                .withHeader(head)//设置JWT头信息
                .withIssuedAt(new Date())    //发行时间
                .withExpiresAt(expiresDate)  //过期时间
                .withClaim("username", username)
//               .withClaim("")
                .sign(Algorithm.HMAC256("Ykqzhengshuai"));

        return token;
    }

    //校验令牌
    public static boolean verifyToken(String token)  {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("Ykqzhengshuai")).build();
            jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            //效验失败
            e.printStackTrace();

        }
        return false;
    }

    //解析token
    public static String getClaimByName(String token){
        String username = JWT.decode(token).getClaim("username").asString();
        return username;
    }
}
